我們知道Java的Logging可以分為日誌門面(Facade)與日誌框架(Logging Framework),使用門面的好處是你可以抽換底層的實作。看到下圖發現還真不少耶,就讓我們往下看看Spring Boot怎麼整合這些日誌吧!


Spring Boot使用Commons Logging作為內部的logging,但當使用Starters時Spring Boot使用的是SLF4J+Logback的組合
Logging是系統一啟動就要使用的,故配置是透過Listener的方式,而xxxAutoConfiguration是系統啟動後進行自動裝配使用的
2023-09-29T03:32:57.262+08:00  INFO 20020 --- [           main] com.swj.Day13LoggingApplication          : Starting Day13LoggingApplication using Java 17.0.7 with PID 20020 (H:\workspace_idea\ironman-2023\day13_logging\target\classes started by James in H:\workspace_idea\ironman-2023)
2023-09-29T03:32:57.265+08:00  INFO 20020 --- [           main] com.swj.Day13LoggingApplication          : No active profile set, falling back to 1 default profile: "default"
logging:
  pattern:
    console: '%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} ===> %msg%n'
2023-09-29 03:47:33.483 INFO  [main] o.a.c.c.StandardService ===> Starting service [Tomcat]
logging:
  level:
    root: "warn"
    org.springframework.web: "debug"
    org.hibernate: "error"
可以將相關的日誌設在同一個組別,Spring Boot提供兩個預設組別
範例如下
logging:
  pattern:
    console: '%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} ===> %msg%n'
  group:
    tomcat: "org.apache.catalina,org.apache.coyote,org.apache.tomcat"
    core-group:
      - "com.swj.controller"
      - "com.swj.service"
  level:
    root: info
    web: debug
    sql: trace
    tomcat: off
    core-group: debug
切換Log實作其實很簡單,只要排除預設的spring-boot-starter-logging,導入其它的就可以了,例如spring-boot-starter-log4j2,以下是maven設定
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
官方文件有說只要在日誌設定檔中加入-spring設定檔就可以被交給Spring來初始化,是不是很方便呢,至於官方文件有提到更多可供設定的Property可點上方標題連結參考
在未設log的file name與file path則log只會在console輸出
如果使用Logback調整File Rotation設定可以直接在application.properties或application.yaml中設置,但是其它日誌框架就要自己寫設定檔了
當使用lombok時,在class上方加上這個註解,就可以用log來寫log了
@Slf4j
public class HelloController {
    //傳統寫法
    //Logger logger = LoggerFactory.getLogger(getClass());
    @GetMapping("/hello")
    public String Hello(){
        log.info("Welcome to Hello api");
        return "Hello";
    }
}